package com.huawei.cce;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iam.v3.region.IamRegion;
import com.huaweicloud.sdk.iam.v3.*;
import com.huaweicloud.sdk.iam.v3.model.*;

import java.util.List;
import java.util.ArrayList;

import java.io.*;
import java.net.URI;
import java.util.*;

/**
 * http请求工具
 */
public class CCEKubernetesNodesAll {


    public static void main(String[] args) {
        CCEKubernetesNodesAll cce = new CCEKubernetesNodesAll();
        //你只需要提供下面这些值，就能获取Kubernetes集群所有节点的信息
        String endPoint,clusterID,uri,url,ak,sk,areaCode,hostUser,user,password,token;

        //下面是各变量值的获取方式：
        //endPoint获取方式参考：https://developer.huaweicloud.com/endpoint获取对应的endPoint值。注意：endpoint值由很多，要找到CCE下面的endpoint
        endPoint = "endpoint";
        //clusterID集群ID需要在华为云控制台的CCE集群管理界面中获取clusterID
        clusterID = "clusterid";
        //资源路径，也是API访问路径,固定不变。
        uri = "/api/v1/nodes";
        //完整路径
        url = "https://"+clusterID + "." + endPoint + uri;
        //ak与sk获取方式可参考：https://support.huaweicloud.com/iam_faq/iam_01_0618.html
        ak = "YOUR AK";
        sk = "YOUR SK";
        //区域码获取方式，参考：https://developer.huaweicloud.com/endpoint
        areaCode = "区域码";
        //hostUser为你的IAM主账户名
        hostUser = "主账户名";
        //user为你的子账户名
        user = "子账户名";
        //密码
        password = "密码";
        //通过以上这些参数获取token
        token = cce.keystoneCreateUserTokenByPassword(ak,sk,areaCode,hostUser,user,password);
        //下面Map可以按需放入可选参数，可选参数可以参考readme.md。
        Map<String,String> param = new HashMap<>();
        //示例。参数可参考https://support.huaweicloud.com/api-cce/cce_02_0179.html
        //参数pretty
        param.put("pretty","true");
        //参数lableSelector
        param.put("labelSelector","name");//这个参数值可以自行配置。
        System.out.println(doGet(url,param,token));
    }
    /**
     * 发送get请求
     * @param url 请求URL
     * @param param 请求参数 key:value url携带参数 或者无参可不填
     * @return
     */
    public static String doGet(String url, Map<String, String> param,String token) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = " ";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            httpGet.addHeader("content-type","application/json");
            httpGet.addHeader("X-Auth-Token",token);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public String keystoneCreateUserTokenByPassword(String ak, String sk, String areaCode, String hostUser, String user, String password){
        String token = null;
        //需要填写你租户下的AK和SK凭证
//        ak = "<YOUR AK>";
//        sk = "<YOUR SK>";

        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        //IamRegion.valueOf("cn-north-4")其中cn-north-4需要改成你的区域
        IamClient client = IamClient.newBuilder()
                .withCredential(auth)
                .withRegion(IamRegion.valueOf(areaCode))
                .build();
        KeystoneCreateUserTokenByPasswordRequest request = new KeystoneCreateUserTokenByPasswordRequest();
        KeystoneCreateUserTokenByPasswordRequestBody body = new KeystoneCreateUserTokenByPasswordRequestBody();
        AuthScopeProject projectScope = new AuthScopeProject();
        //projectScope.withName("")需要改写成你的区域
        projectScope.withName(areaCode);
        AuthScope scopeAuth = new AuthScope();
        scopeAuth.withProject(projectScope);
        PwdPasswordUserDomain domainUser = new PwdPasswordUserDomain();
        //withName()需要填入主租户名。
        domainUser.withName(hostUser);
        PwdPasswordUser userPassword = new PwdPasswordUser();
        //withName()需要填入用户名。withPassword()需要填入密码
        userPassword.withDomain(domainUser)
                .withName(user)
                .withPassword(password);
        PwdPassword passwordIdentity = new PwdPassword();
        passwordIdentity.withUser(userPassword);
        List<PwdIdentity.MethodsEnum> listIdentityMethods = new ArrayList<>();
        listIdentityMethods.add(PwdIdentity.MethodsEnum.fromValue("password"));
        PwdIdentity identityAuth = new PwdIdentity();
        identityAuth.withMethods(listIdentityMethods)
                .withPassword(passwordIdentity);
        PwdAuth authbody = new PwdAuth();
        authbody.withIdentity(identityAuth)
                .withScope(scopeAuth);
        body.withAuth(authbody);
        request.withBody(body);
        try {
            KeystoneCreateUserTokenByPasswordResponse response = client.keystoneCreateUserTokenByPassword(request);
//            System.out.println(response.toString());
//            System.out.println("你的token为：");
            token = response.getXSubjectToken();
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return token;
    }
}
